from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render, get_object_or_404
from django.urls import reverse
from django.utils import timezone
from accounts.models import User
from .models import ScheduledTask, TaskExecutionLog
from .forms import ScheduledTaskForm, TaskExecutionLogFilterForm
import subprocess
import os
import sys

@login_required
def scheduled_task_list(request):
    """
    定时任务列表视图
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限访问此页面')
        return redirect('projects:dashboard')
    
    # 获取所有定时任务
    tasks = ScheduledTask.objects.all().order_by('-created_at')
    
    # 计算统计数据
    total_tasks = tasks.count()
    active_tasks = tasks.filter(is_active=True).count()
    inactive_tasks = tasks.filter(is_active=False).count()
    
    # 计算24小时内的执行次数
    last_24h = timezone.now() - timezone.timedelta(hours=24)
    last_24h_executions = TaskExecutionLog.objects.filter(start_time__gte=last_24h).count()
    
    # 分页处理
    paginator = Paginator(tasks, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'title': '定时任务管理',
        'total_tasks': total_tasks,
        'active_tasks': active_tasks,
        'inactive_tasks': inactive_tasks,
        'last_24h_executions': last_24h_executions,
    }
    
    return render(request, 'tasks/scheduled_task_list.html', context)

@login_required
def scheduled_task_create(request):
    """
    创建定时任务视图
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限执行此操作')
        return redirect('projects:dashboard')
    
    if request.method == 'POST':
        form = ScheduledTaskForm(request.POST, user=request.user)
        if form.is_valid():
            task = form.save(commit=False)
            task.created_by = request.user
            task.updated_by = request.user
            task.save()
            
            messages.success(request, '定时任务创建成功')
            return redirect('tasks:scheduled_task_list')
    else:
        form = ScheduledTaskForm(user=request.user)
    
    context = {
        'form': form,
        'title': '创建定时任务',
        'action': 'create',
    }
    
    return render(request, 'tasks/scheduled_task_form.html', context)

@login_required
def scheduled_task_edit(request, task_id):
    """
    编辑定时任务视图
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限执行此操作')
        return redirect('projects:dashboard')
    
    task = get_object_or_404(ScheduledTask, pk=task_id)
    
    if request.method == 'POST':
        form = ScheduledTaskForm(request.POST, instance=task, user=request.user)
        if form.is_valid():
            task = form.save(commit=False)
            task.updated_by = request.user
            task.save()
            
            messages.success(request, '定时任务更新成功')
            return redirect('tasks:scheduled_task_list')
    else:
        form = ScheduledTaskForm(instance=task, user=request.user)
    
    context = {
        'form': form,
        'title': '编辑定时任务',
        'action': 'edit',
        'task': task,
    }
    
    return render(request, 'tasks/scheduled_task_form.html', context)

@login_required
def scheduled_task_delete(request, task_id):
    """
    删除定时任务视图
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限执行此操作')
        return redirect('projects:dashboard')
    
    task = get_object_or_404(ScheduledTask, pk=task_id)
    
    if request.method == 'POST':
        task_name = task.name
        task.delete()
        
        messages.success(request, f'定时任务"{task_name}"已成功删除')
        return redirect('tasks:scheduled_task_list')
    
    context = {
        'task': task,
        'title': '删除定时任务',
    }
    
    return render(request, 'tasks/scheduled_task_confirm_delete.html', context)

@login_required
def task_execution_logs(request):
    """
    任务执行日志列表视图
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限访问此页面')
        return redirect('projects:dashboard')
    
    logs = TaskExecutionLog.objects.all().order_by('-start_time')
    
    # 处理过滤表单
    form = TaskExecutionLogFilterForm(request.GET)
    if form.is_valid():
        if form.cleaned_data['task']:
            logs = logs.filter(task=form.cleaned_data['task'])
        if form.cleaned_data['start_date']:
            logs = logs.filter(start_time__date__gte=form.cleaned_data['start_date'])
        if form.cleaned_data['end_date']:
            logs = logs.filter(start_time__date__lte=form.cleaned_data['end_date'])
        if form.cleaned_data['is_success'] is not None:
            logs = logs.filter(is_success=form.cleaned_data['is_success'])
    
    # 分页处理
    paginator = Paginator(logs, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'form': form,
        'title': '任务执行日志',
    }
    
    return render(request, 'tasks/task_execution_logs.html', context)

@login_required
def task_execution_log_delete(request, log_id):
    """
    删除单个任务执行日志视图
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限执行此操作')
        return redirect('projects:dashboard')
    
    log = get_object_or_404(TaskExecutionLog, pk=log_id)
    
    if request.method == 'POST':
        log.delete()
        messages.success(request, '任务执行日志已成功删除')
        # 获取原始过滤参数，以便重定向回过滤后的列表
        query_params = request.GET.copy()
        if 'page' in query_params:
            del query_params['page']  # 删除page参数，避免可能的无效页面
        url = reverse('tasks:task_execution_logs') + '?' + query_params.urlencode()
        return redirect(url)
    
    context = {
        'log': log,
        'title': '确认删除任务执行日志',
    }
    
    return render(request, 'tasks/task_execution_log_delete.html', context)

@login_required
def task_execution_logs_bulk_delete(request):
    """
    批量删除任务执行日志视图
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限执行此操作')
        return redirect('projects:dashboard')
    
    if request.method == 'POST':
        # 获取选中的日志ID列表
        log_ids = request.POST.getlist('selected_logs')
        if log_ids:
            # 转换为整数列表
            log_ids = [int(log_id) for log_id in log_ids]
            # 删除选中的日志
            logs = TaskExecutionLog.objects.filter(id__in=log_ids)
            logs.delete()
            messages.success(request, f'成功删除了{len(log_ids)}条任务执行日志')
        else:
            messages.warning(request, '请至少选择一条日志进行删除')
        
        # 获取原始过滤参数，以便重定向回过滤后的列表
        query_params = request.GET.copy()
        if 'page' in query_params:
            del query_params['page']  # 删除page参数，避免可能的无效页面
        url = reverse('tasks:task_execution_logs') + '?' + query_params.urlencode()
        return HttpResponseRedirect(url)
    
    # 如果不是POST请求，重定向回日志列表页
    return redirect('tasks:task_execution_logs')

@login_required
def task_execution_log_detail(request, log_id):
    """
    任务执行日志详情视图
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限访问此页面')
        return redirect('projects:dashboard')
    
    log = get_object_or_404(TaskExecutionLog, pk=log_id)
    
    context = {
        'log': log,
        'title': '任务执行日志详情',
    }
    
    return render(request, 'tasks/task_execution_log_detail.html', context)

@login_required
def task_execute_now(request, task_id):
    """
    立即执行定时任务
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限执行此操作')
        return redirect('projects:dashboard')
    
    task = get_object_or_404(ScheduledTask, pk=task_id)
    
    # 检查任务是否激活
    if not task.is_active:
        messages.warning(request, f'定时任务"{task.name}"未激活，无法执行')
        return redirect('tasks:scheduled_task_list')
    
    # 创建执行日志
    log_entry = TaskExecutionLog.objects.create(
        task=task,  # 设置关联的定时任务
        start_time=timezone.now(),
        is_success=False
    )
    
    # 导入并执行任务
    try:
        # 导入并执行collect_and_push_pending_items任务
        from tasks.tasks import collect_and_push_pending_items
        
        # 直接执行任务（同步执行，适用于当前配置）
        result = collect_and_push_pending_items()
        
        # 更新执行日志
        log_entry.end_time = timezone.now()
        log_entry.is_success = True
        log_entry.log_content = f'手动执行成功\n执行结果: {result}'
        log_entry.total_processed = result.get('total_processed', 0)
        log_entry.success_count = result.get('success_count', 0)
        log_entry.failure_count = result.get('failure_count', 0)
        log_entry.save()
        
        # 更新任务最后执行信息
        task.last_executed_at = timezone.now()
        task.last_execution_status = True
        task.last_execution_log = f'手动执行成功，处理了{result.get("total_processed", 0)}个项目'
        task.save()
        
        messages.success(request, f'定时任务"{task.name}"执行成功！处理了{result.get("total_processed", 0)}个项目，成功推送{result.get("success_count", 0)}个')
    except Exception as e:
        # 如果出错，更新日志
        log_entry.end_time = timezone.now()
        log_entry.is_success = False
        log_entry.error_message = str(e)
        log_entry.save()
        
        messages.error(request, f'执行定时任务失败：{str(e)}')
        
        # 更新任务最后执行信息
        task.last_executed_at = timezone.now()
        task.last_execution_status = False
        task.last_execution_log = f'手动执行失败：{str(e)}'
        task.save()
    
    return redirect('tasks:scheduled_task_list')

@login_required
def scheduled_task_toggle_status(request, task_id):
    """
    切换定时任务的启用/禁用状态
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限执行此操作')
        return redirect('projects:dashboard')
    
    task = get_object_or_404(ScheduledTask, pk=task_id)
    
    # 切换状态
    task.is_active = not task.is_active
    task.updated_by = request.user
    task.save()
    
    status_text = '启用' if task.is_active else '禁用'
    messages.success(request, f'定时任务"{task.name}"已{status_text}')
    
    return redirect('tasks:scheduled_task_list')

@login_required
def restart_task_scheduler(request):
    """
    手动重启任务管理器
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限执行此操作')
        return redirect('projects:dashboard')
    
    try:
        # 导入必要的模块
        from .tasks import register_scheduled_tasks
        
        # 重新注册所有定时任务
        register_scheduled_tasks()
        
        # 添加执行日志
        log_entry = TaskExecutionLog.objects.create(
            start_time=timezone.now(),
            is_success=True,
            log_content="手动重启任务管理器成功"
        )
        
        messages.success(request, '任务管理器已成功重启，所有定时任务已重新加载')
    except Exception as e:
        # 添加错误日志
        log_entry = TaskExecutionLog.objects.create(
            start_time=timezone.now(),
            is_success=False,
            error_message=str(e),
            log_content="手动重启任务管理器失败"
        )
        
        messages.error(request, f'重启任务管理器失败：{str(e)}')
    
    return redirect('tasks:scheduled_task_list')

@login_required
def restart_all_services(request):
    """
    通过控制台重启所有服务（Django服务器、Celery Worker和Celery Beat）
    仅限超级管理员访问
    """
    # 检查用户是否为超级管理员
    if not request.user.is_super_admin():
        messages.error(request, '您没有权限执行此操作')
        return redirect('projects:dashboard')
    
    try:
        # 执行start_services.py脚本，并传递restart参数
        script_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'start_services.py')
        
        # 在Windows系统上使用pythonw.exe以避免控制台窗口
        if os.name == 'nt':
            subprocess.Popen([sys.executable, script_path, 'restart'], shell=True, creationflags=subprocess.CREATE_NEW_CONSOLE)
        else:
            subprocess.Popen(['python', script_path, 'restart'], shell=True)
            
        # 添加执行日志
        log_entry = TaskExecutionLog.objects.create(
            start_time=timezone.now(),
            is_success=True,
            log_content="通过控制台重启所有服务成功"
        )
        
        messages.success(request, '所有服务正在重启，请查看新打开的窗口了解重启状态')
    except Exception as e:
        # 添加错误日志
        log_entry = TaskExecutionLog.objects.create(
            start_time=timezone.now(),
            is_success=False,
            error_message=str(e),
            log_content="通过控制台重启所有服务失败"
        )
        
        messages.error(request, f'重启服务失败：{str(e)}')
    
    return redirect('tasks:scheduled_task_list')
